import re
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework.viewsets import ModelViewSet

from car.helpers import CustomPagination, RecordFilter
from car.models import Record
from car.serializers import RecordSerializer


# @cache_page(timeout=86400, cache='default', key_prefix='page:home')
def home(request):
    return render(request, 'search.html')


# FBV - Function-Based View - 灵活完全自己定制但代码较多
# @api_view(['GET', 'POST'])
# def search(request):
#     if request.method == 'POST':
#         pass
#         # record = Record()
#         # record.save()
#         # serializer = RecordSerializer(record)
#     else:
#         queryset = Record.objects.all()
#         serializer = RecordSerializer(queryset, many=True)
#     return Response(serializer.data)


# CBV - Class-Based View - 代码量少简单方便
# path('records/', SearchView.as_view())
# class SearchView(ListCreateAPIView, DestroyAPIView):
#     queryset = Record.objects.all()
#     serializer_class = RecordSerializer


# router = DefaultRouter()
# router.register('records', SearchViewSet)
# urlpatterns += router.urls
# @method_decorator(decorator=cache_page(timeout=120, cache='default', key_prefix='records'), name='list')
# @method_decorator(decorator=cache_page(timeout=60, cache='default', key_prefix='record'), name='retrieve')
class SearchViewSet(ModelViewSet):
    queryset = Record.objects.all()
    serializer_class = RecordSerializer
    pagination_class = CustomPagination
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    # filterset_fields = ('carno', 'owner')
    filterset_class = RecordFilter
    ordering = ('-makedate', )
    ordering_fields = ('carno', 'makedate')

    # def get_queryset(self):
    #     q = Q()
    #     carno = self.request.query_params.get('carno')
    #     if carno:
    #         carno = normalize_carno(carno)
    #         q |= Q(carno=carno)
    #     owner = self.request.query_params.get('owner')
    #     if owner:
    #         q |= Q(owner__icontains=owner)
    #     return self.queryset.filter(q)


# @csrf_exempt
# def search(request: HttpRequest) -> HttpResponse:
#     if request.method == 'GET':
#         return render(request, 'search.html')
#     else:
#         carno = request.POST.get('carno', '')
#         carno = normalize_carno(carno)
#         if CARNO_PATTERN.match(carno) or NAME_PATTERN.match(carno):
#             queryset = Record.objects\
#                 .filter(Q(carno=carno) | Q(owner__startswith=carno))\
#                 .order_by('-makedate')
#             records = []
#             for elem in queryset:
#                 props = ['no', 'carno', 'owner', 'reason', 'makedate', 'punish', 'dealed']
#                 record = {}
#                 for prop in props:
#                     value = getattr(elem, prop, '')
#                     if prop == 'makedate':
#                         value = value.strftime('%Y-%m-%d %H:%M:%S')
#                     record[prop] = value
#                 records.append(record)
#             data = {'code': 200, 'records': records}
#         else:
#             data = {'code': 400, 'hint': '请输入有效的车牌号或车主姓名'}
#         return JsonResponse(data)


# def handle_or_delete(request):
#     record_no = request.GET.get('no', '')
#     if record_no:
#         record = Record.objects.filter(no=record_no).first()
#         if record:
#             if request.path.startswith('/delete'):
#                 record.delete()
#                 data = {'code': 204, 'hint': '删除成功'}
#             else:
#                 record.dealed = True
#                 record.save()
#                 data = {'code': 200, 'hint': '受理成功'}
#         else:
#             data = {'code': 404, 'hint': '没有对应的违章记录'}
#     else:
#         data = {'code': 400, 'hint': '无效的违章记录号'}
#     return JsonResponse(data)
